#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os
import sys
import zipfile
from xml.dom.minidom import Document
import shutil
import fileUtils


def copy_file(source_file, new_apk_file):
    origin_zip = zipfile.ZipFile(source_file, 'r')
    out_zip = zipfile.ZipFile(new_apk_file, 'w')
    for item in origin_zip.infolist():
        buffer = origin_zip.read(item.filename)
        if "SHANPAO.RSA" in item.filename:
            continue
        else:
            out_zip.writestr(item, buffer)
    out_zip.close()
    origin_zip.close()


py_home = os.path.dirname(os.path.realpath(sys.argv[0]))
print(py_home)

# 读取原始apk
source_folder = py_home + os.sep + "origin_apk"
source_file = ""
source_files = os.listdir(source_folder)
if len(source_files) == 0:
    print("请在origin_apk目录存放apk")
    sys.exit(0)
elif len(source_files) > 1:
    print("请在origin_apk目录中只存放一个apk")
    sys.exit(0)
else:
    source_file = source_files[0]

# 解析出apk名称
origin_apk_name = source_file
if os.sep in origin_apk_name:
    name_split = origin_apk_name.split(os.sep)
    origin_apk_name = name_split[len(name_split) - 1].replace(".apk", "")

if not origin_apk_name.endswith(".apk"):
    print("请带上原文件的路径或文件名")

print("origin_apk_name = " + origin_apk_name)

# 找出rsa压缩包
rsa_folder = py_home + os.sep + "signed_rsa"
fileUtils.mkdir(rsa_folder)
rsa_zip = ""
rsa_files = os.listdir(rsa_folder)
for rsa_file in rsa_files:
    if not rsa_file.endswith(".zip"):
        fileUtils.delete_file(rsa_folder + os.sep + rsa_file)


if len(rsa_files) == 0:
    print("请将rsa压缩包放到signed_rsa目录下")
    sys.exit(0)
elif len(rsa_files) > 1:
    print("请在signed_rsa目录中只存放一个rsa压缩包")
    print(rsa_files)
    sys.exit(0)
else:
    rsa_zip = rsa_folder + os.sep + rsa_files[0]

channel_file_path = py_home + os.sep + 'UMENG_CHANNEL_NUM.txt'

# 生成最终的apk的文件夹
channel_apk_folder_name = "channel_apk"
print(py_home + os.sep + channel_apk_folder_name)
if not os.path.exists(py_home + os.sep + channel_apk_folder_name):
    os.mkdir(py_home + os.sep + channel_apk_folder_name)
apk_list = os.listdir(py_home + os.sep + channel_apk_folder_name)

# 读取所有的渠道映射
channel_map = {}
with open(channel_file_path, "tr", encoding="utf-8") as f:  # 打开文件
    # 按行读取文件
    channel_list = f.readlines()
    print(channel_list)
    for line in channel_list:
        line = line.strip('\n')  # 去掉列表中每一个元素的换行符
        channel_id = line.split("##")
        channel_name = channel_id[1]
        channel_code = channel_id[0]
        channel_map[channel_code] = channel_name

rsa_zip_file = zipfile.ZipFile(rsa_zip, 'r', zipfile.ZIP_DEFLATED)
target_apk_folder = "final_apk"
fileUtils.delete_folder(target_apk_folder)
fileUtils.mkdir(target_apk_folder)
count = 0
# 获取apk列表
for apk_file in apk_list:
    channel_apk_path = py_home + os.sep + channel_apk_folder_name + os.sep + apk_file
    print("channel_apk_path = " + channel_apk_path)
    namelist = rsa_zip_file.namelist()

    # 遍历rsa压缩包
    for rsa_file in rsa_zip_file.filelist:
        # 提取rsa文件到rsa_temp目录下
        # 提取rsa到
        extract = rsa_zip_file.extract(rsa_file.filename, py_home + os.sep + "rsa_temp")
        split = rsa_file.filename.split("_")
        ras_channel_code = split[0]
        rsa_name = split[1]
        try:
            if "__MACOSX" in ras_channel_code:
                continue
            channel_name = channel_map[ras_channel_code]
        except BaseException as e:
            continue
        new_rsa_file = py_home + os.sep + "rsa_temp" + os.sep + rsa_file.filename
        if not os.path.exists(new_rsa_file):
            print("rsa渠道文件不存在，跳过 " + apk_file + "的rsa文件写入")
            break
        # 名称匹配
        if ras_channel_code in apk_file:
            channel_apk_path = py_home + os.sep + "channel_apk" + os.sep + apk_file

            if channel_name == "":
                continue
            target_apk = py_home + os.sep + target_apk_folder + os.sep + origin_apk_name + "_" + channel_name + ".apk"
            print("target_apk = " + target_apk)
            # 复制apk文件
            print("正在复制apk")
            copy_file(channel_apk_path, target_apk)
            zip = zipfile.ZipFile(target_apk, 'a', zipfile.ZIP_DEFLATED)
            rsa_file_path_in_apk = os.sep + "META-INF" + os.sep + "SHANPAO.RSA"
            # 将新rsa文件写入到目标文件apk包
            print("正在写入rsa文件到apk")
            zip.write(new_rsa_file, rsa_file_path_in_apk)
            zip.close()
            count = count + 1
            print("已完成" + str(count) + "个文件")

print("正在为您打开渠道apk目录")
fileUtils.open_path(py_home + os.sep + target_apk_folder)
